package org.feifei.org.service.impl;

import org.feifei.basic.service.impl.BaseServiceImpl;
import org.feifei.basic.util.PageList;
import org.feifei.org.domain.Department;
import org.feifei.org.mapper.DepartmentMapper;
import org.feifei.org.query.DepartmentQuery;
import org.feifei.org.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * DepartmentService 的实现类，实现了所有方法
 */
@Transactional(readOnly = false, propagation = Propagation.SUPPORTS)
@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements DepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    /** 添加方法或者修改的方法 */
    @Override
    @Transactional
    public void save(Department department) {
        if (department.getId() == null) {
            if(department.getParent()==null || department.getParent().getId() == null){//你没有选择上级部门
                department.setDirPath("/" + department.getId());
            }else{
                Long id = department.getParent().getId(); //上级部门的id
                Department parentDept = departmentMapper.get(id);
                //上级部门的dirPath
                String dirPath = parentDept.getDirPath();
                //设置自己的dirPath
                department.setDirPath(dirPath + "/" + department.getId());
            }

            departmentMapper.save(department);
        }
        else {
            if(department.getParent()==null || department.getParent().getId() == null){//你没有选择上级部门
                department.setDirPath("/" + department.getId());
            }else{
                Long id = department.getParent().getId(); //上级部门的id
                Department parentDept = departmentMapper.get(id);
                //上级部门的dirPath
                String dirPath = parentDept.getDirPath();
                //设置自己的dirPath
                department.setDirPath(dirPath + "/" + department.getId());
            }
            departmentMapper.update(department);
        }
    }

    @Override
    public List<Department> getDepartTree() {
        return departmentMapper.getDepartTree();
    }
}
